<?php

declare(strict_types=1);
/**
 * 作者：薛原
 * 功能：个人文章控制器
 * 时间：2025/10/17
 */
namespace App\Controller\v1;

use App\Service\ArticleService;
use Hyperf\Context\Context;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\Di\Annotation\Inject;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\Middleware;

#[Controller(prefix: "/api/v1/articles")]

#[Middleware(\App\Middleware\TokenMiddleware::class)]

class ArticlesController extends AbstractController
{

    #[Inject]
    private ArticleService $articleService;

    /**
     * 文章列表接口
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[GetMapping("")]
    public function index(RequestInterface $request): array|\Psr\Http\Message\ResponseInterface
    {
        $params = $this->parseParams($request);
        $size = isset($params['size'])?$params['size']:20;
        $page = isset($params['page'])?$params['page']:1;
        $user_id = Context::get("login_user_id")."";
        try{
            $ret = $this->articleService->getArticleList($user_id, $size, $page);

        }catch (\App\Exception\BusinessException $e){
            return $this->fail(["msg"=>"请求失败","errors"=>$e->getMessage()]);
        }
        return $this->success($ret,"请求成功");
    }

    /**
     * 文章创建接口
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[PostMapping("")]
    public function create(RequestInterface $request): array|\Psr\Http\Message\ResponseInterface
    {
        $user_id = Context::get("login_user_id")."";
        $params = $this->parseParams($request);
        $data['title'] = $params['title'];
        $data['content'] = $params['content'];
        $data['cover_image'] = isset($params['cover_image']) ? $params['cover_image'] : "";
        $data['tags'] = isset($params['tags']) ? $params['tags'] : [];
        $data['content_type'] = isset($params['content_type']) ? $params['content_type'] : "markdown";
        try{
            $article_id = $this->articleService->createArticle($data, $user_id);
            $ret = $this->articleService->getArticleById($article_id);

        }catch (\App\Exception\BusinessException $e){
            return $this->fail(40002,"请求失败",["errors"=>$e->getMessage()]);
        }
        return $this->success($ret,"请求成功");
    }

    /**
     * 文章更新接口
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[PutMapping("{id}")]
    public function edit(RequestInterface $request, $id): array|\Psr\Http\Message\ResponseInterface
    {
        $article_id = $id;
        $user_id = Context::get("login_user_id")."";
        $params = $this->parseParams($request);
        $data['title'] = $params['title'];
        $data['content'] = $params['content'];
        $data['cover_image'] = isset($params['cover_image']) ? $params['cover_image'] : "";
        $data['tags'] = isset($params['tags']) ? $params['tags'] : [];
        try{
            $article_id = $this->articleService->updateArticle($article_id, $data, $user_id);
            $ret = $this->articleService->getArticleById($article_id);

        }catch (\App\Exception\BusinessException $e){
            return $this->fail(40002,"请求失败",["errors"=>$e->getMessage()]);
        }
        return $this->success($ret,"请求成功");
    }

    /**
     * 文章删除接口
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[DeleteMapping('{id}')]
    public function delete(RequestInterface $request, $id): array|\Psr\Http\Message\ResponseInterface
    {
        $user_id = Context::get("login_user_id")."";
        $article_id = $id;
        try{
            $this->articleService->deleteArticle($article_id, $user_id);
        }catch (\App\Exception\BusinessException $e){
            return $this->fail(40002,"请求失败",["errors"=>$e->getMessage()]);
        }
        return $this->success(null,"文章删除成功");
    }

    /**
     * 文章提交审核接口
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[PostMapping('{id}/review')]
    public function submit(RequestInterface $request, $id): array|\Psr\Http\Message\ResponseInterface
    {
        $user_id = Context::get("login_user_id")."";
        $article_id = $id;
        try{
            $this->articleService->submitArticle($article_id, $user_id);
        }catch (\App\Exception\BusinessException $e){
            return $this->fail(40002,"请求失败",["errors"=>$e->getMessage()]);
        }
        return $this->success(null,"提交审核成功");
    }

    /**
     * 获取用户收藏夹列表
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[GetMapping("folders")]
    public function folders(): array|\Psr\Http\Message\ResponseInterface
    {
        $user_id = Context::get("login_user_id")."";
        if (!$user_id) {
            return $this->fail(401, "未授权", null);
        }
        
        try{
            $ret = $this->articleService->getUserFolders((int)$user_id);
        }catch (\Throwable $e){
            return $this->fail(40002, "请求失败", $e->getMessage());
        }
        return $this->success($ret, "请求成功");
    }

    /**
     * 文章详情接口
     * 暂时无需鉴权
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[GetMapping('{id}')]
    public function detail(RequestInterface $request, $id): array|\Psr\Http\Message\ResponseInterface
    {
        $article_id = $id;
        $user_id = Context::get("login_user_id")."";
        try {
            $ret = $this->articleService->getArticleById($article_id, $user_id);
            if($ret['user_id'] != $user_id){
                return $this->fail(40002, "请求失败", ["errors" => "不能看非自己的文章"]);
            }
        } catch (\App\Exception\BusinessException $e) {
            return $this->fail(40002, "请求失败", ["errors" => $e->getMessage()]);
        }
        return $this->success($ret, "success");
    }
    /**
     * 点赞/取消点赞文章
     * @param int $id
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[PostMapping("/{id}/like")]
    public function like(int $id): array|\Psr\Http\Message\ResponseInterface
    {
        $user_id = Context::get("login_user_id")."";
        if (!$user_id) {
            return $this->fail(401, "未授权", null);
        }
        try{
            $ret = $this->articleService->toggleLike((int)$id, (int)$user_id);
        }catch (\Throwable $e){
            return $this->fail(40002, "请求失败", $e->getMessage());
        }
        return $this->success($ret, $ret['liked'] ? "点赞成功" : "取消点赞成功");
    }
    /**
     * 点赞用户列表
     * @param RequestInterface $request
     * @param int $id
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[GetMapping("/{id}/likes")]
    public function likeUsers(RequestInterface $request, int $id): array|\Psr\Http\Message\ResponseInterface
    {
        $params = $this->parseParams($request);
        $size = isset($params['size'])?$params['size']:20;
        $page = isset($params['page'])?$params['page']:1;

        try{
            $ret = $this->articleService->getArticleLikeUsers((int)$id, $size, $page);
        }catch (\Throwable $e){
            return $this->fail(40002, "请求失败", $e->getMessage());
        }
        return $this->success($ret, "请求成功");
    }

    /**
     * 收藏/取消收藏文章
     * @param int $id
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[PostMapping("/{id}/favorite")]
    public function favorite(int $id, RequestInterface $request): array|\Psr\Http\Message\ResponseInterface
    {
        $user_id = Context::get("login_user_id")."";
        if (!$user_id) {
            return $this->fail(401, "未授权", null);
        }

        $params = $this->parseParams($request);
        $folder_id = $params['folder_id'];
        try{
            $ret = $this->articleService->toggleFavorite((int)$id, (int)$user_id, $folder_id ? (int)$folder_id : null);
        }catch (\Throwable $e){
            return $this->fail(40002, "请求失败", $e->getMessage());
        }
        return $this->success($ret, $ret['favorited'] ? "收藏成功" : "取消收藏成功");
    }

    /**
     * 创建收藏夹
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[PostMapping("folders")]
    public function createFolder(RequestInterface $request): array|\Psr\Http\Message\ResponseInterface
    {
        $user_id = Context::get("login_user_id")."";
        if (!$user_id) {
            return $this->fail(401, "未授权", null);
        }

        $params = $this->parseParams($request);
        $name = $params['name'];
        $is_public = (bool)$params['is_public'];
        
        if (!$name) {
            return $this->fail(40002, "收藏夹名称不能为空", null);
        }
        
        try{
            $ret = $this->articleService->createFolder((int)$user_id, $name, $is_public);
        }catch (\Throwable $e){
            return $this->fail(40002, "请求失败", $e->getMessage());
        }
        return $this->success($ret, "创建成功");
    }

    /**
     * 更新收藏夹
     * @param int $folderId
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[PutMapping("folders/{folderId}")]
    public function updateFolder(int $folderId, RequestInterface $request): array|\Psr\Http\Message\ResponseInterface
    {
        $user_id = Context::get("login_user_id")."";
        if (!$user_id) {
            return $this->fail(401, "未授权", null);
        }
        $data = $this->parseParams($request);
        try{
            $ret = $this->articleService->updateFolder($folderId, (int)$user_id, $data);
        }catch (\Throwable $e){
            return $this->fail(40002, "请求失败", $e->getMessage());
        }
        return $this->success($ret, "更新成功");
    }

    /**
     * 删除收藏夹
     * @param int $folderId
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[DeleteMapping("folders/{folderId}")]
    public function deleteFolder(int $folderId): array|\Psr\Http\Message\ResponseInterface
    {
        $user_id = Context::get("login_user_id")."";
        if (!$user_id) {
            return $this->fail(401, "未授权", null);
        }
        
        try{
            $this->articleService->deleteFolder($folderId, (int)$user_id);
        }catch (\Throwable $e){
            return $this->fail(40002, "请求失败", $e->getMessage());
        }
        return $this->success([], "删除成功");
    }

    /**
     * 获取收藏夹中的文章列表
     * @param int $folderId
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[GetMapping("folders/{folderId}/articles")]
    public function folderArticles(int $folderId, RequestInterface $request): array|\Psr\Http\Message\ResponseInterface
    {
        $user_id = Context::get("login_user_id")."";
        $params = $this->parseParams($request);
        if (!$user_id) {
            return $this->fail(401, "未授权", null);
        }

        $size = isset($params['size'])?$params['size']:20;
        $page = isset($params['page'])?$params['page']:1;
        
        try{
            $ret = $this->articleService->getFolderArticles($folderId, (int)$user_id, $size, $page);
        }catch (\Throwable $e){
            return $this->fail(40002, "请求失败", $e->getMessage());
        }
        return $this->success($ret, "请求成功");
    }

    /**
     * 导出收藏列表
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[GetMapping("favorites/export")]
    public function exportFavorites(RequestInterface $request): array|\Psr\Http\Message\ResponseInterface
    {
        $params = $this->parseParams($request);
        $user_id = Context::get("login_user_id")."";
        if (!$user_id) {
            return $this->fail(401, "未授权", null);
        }
        $folder_id = $params['folder_id'];
        
        try{
            $ret = $this->articleService->exportFavorites((int)$user_id, $folder_id ? (int)$folder_id : null);
        }catch (\Throwable $e){
            return $this->fail(40002, "请求失败", $e->getMessage());
        }
        return $this->success($ret, "导出成功");
    }
}
